package com.qf.Listener;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * author:z
 * time:2021/12/17 16:09
 * description:
 */
//@Component
@RabbitListener(queues = "boot-queue1")
public class QueueListener {

    @Autowired
    StringRedisTemplate redisTemplate;

    @RabbitHandler
    public void onMessage(String msg, Channel channel,Message message) throws IOException {

        //0. 获取MessageId, 消息唯一id
        /**
         *如果redis中不存在此 messageId，说明此消息没有消费者，正常消费即可
         */
        String messageId = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
        if (redisTemplate.opsForValue().setIfAbsent(messageId,"0",5, TimeUnit.MINUTES)) {
            System.out.println("队列1："+msg);
            redisTemplate.opsForValue().set(messageId,"1",5,TimeUnit.MINUTES);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }else {
            String s = redisTemplate.opsForValue().get(messageId);
            //如果messageId对应的值为0，说明正在被消费，什么都不需要做
            //如果messageId对应的值为1，说明消费成功，手动ack
            if("1".equalsIgnoreCase(s)){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        }
//        System.out.println("message-----1:"+msg);
//        try {
//            int i=1/0;
//            //参数1：消息的唯一标识
//            //参数2：是否开启批量处理
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//        }catch (Exception e){
//            e.printStackTrace();
//            //参数1：消息的唯一标识
//            //参数2：失败后当前消费着是否拒绝
//            //参数3：是否回到原队列
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
//        }
    }
}
